<?php

class GroupRepository {

    var $db;

    public function GroupRepository() {
        global $SERVER, $DATABASE, $USERNAME, $PASSWORD;
        $this->db = new Connection($SERVER, $DATABASE, $USERNAME, $PASSWORD);
    }

    public function GetAll() {
        $query = "SELECT * FROM `group`";
        return $this->ConvertToList($this->db->ExecuteQuery($query));
    }

    public function ConvertToList($result) {
        $list = array();
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            $list[] = new GroupEntity($row[0], $row[1]);
        }
        return $list;
    }

    public function InsertGroup($groupName) {
        $query = "INSERT INTO `group` (Name_s) VALUES ('" . $groupName . "')";
        $result = $this->db->ExecuteQuery($query) or die("Query failed with error: " . mysql_error());
        if ($result != 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function InsertGroupAuthority($groupID, $authorityID) {
        $query = "INSERT INTO `group_authority` (GroupID_i,AuthorityID_i) VALUES (" . $groupID . "," . $authorityID . ")";
        $result = $this->db->ExecuteQuery($query) or die("Query failed with error: " . mysql_error());
        if ($result != 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function CheckGroupNameExist($groupName) {
        $query = "SELECT * FROM `group` WHERE Name_s LIKE '" . $groupName . "'";
        if ($this->db->ExecuteQuery($query)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function CreateGroup($groupName, array $list) {
        mysql_query('BEGIN');
        if ($this->InsertGroup($groupName)) {
            $groupID = mysql_insert_id();
            for ($i = 0; $i < count($list); $i++) {
                if (!$this->InsertGroupAuthority($groupID, $list[$i])) {
                    mysql_query("ROLLBACK");
                    return FALSE;
                }
            }
            mysql_query("COMMIT");
            return TRUE;
        } else {
            mysql_query("ROLLBACK");
            return FALSE;
        }
    }

    public function DeleteGroup($groupID) {
        $query = "DELETE FROM `group` WHERE ID_i = " . $groupID;
        $result = $this->db->ExecuteQuery($query) or die("Query failed with error:" . mysql_error());
        if ($result != 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

}

?>
